package repository

import (
	"time"

	"gitee.com/fx8s/goIrisTest/src/modules/profile/model"
	mgo "gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

//ProfilRepositoryMongo
type profilRepositoryMongo struct {
	db         *mgo.Database
	collection string
}

//NewProfilRepositoryMongo
func NewProfilRepositoryMongo(db *mgo.Database, collection string) *profilRepositoryMongo {
	return &profilRepositoryMongo{
		db:         db,
		collection: collection,
	}
}

// Save
func (r *profilRepositoryMongo) Save(profile *model.Profile) error {
	err := r.db.C(r.collection).Insert(profile)
	return err
}

// Update
func (r *profilRepositoryMongo) Update(id string, profile *model.Profile) error {
	profile.UpdateAt = time.Now()
	err := r.db.C(r.collection).Update(bson.M{"id": id}, profile)
	return err
}

// Delete
func (r *profilRepositoryMongo) Delete(id string) error {
	err := r.db.C(r.collection).Remove(bson.M{"id": id})
	return err
}

// FindById
func (r *profilRepositoryMongo) FindById(id string) (*model.Profile, error) {
	var profile model.Profile
	err := r.db.C(r.collection).Find(bson.M{"id": id}).One(&profile)

	if err != nil {
		return nil, err
	}

	return &profile, nil
}

// FindByEmail
func (r *profilRepositoryMongo) FindByEmail(email string) (*model.Profile, error) {
	var profile model.Profile
	err := r.db.C(r.collection).Find(bson.M{"email": email}).One(&profile)

	if err != nil {
		return nil, err
	}

	return &profile, nil
}

// FindAll
func (r *profilRepositoryMongo) FindAll() (model.Profiles, error) {
	var profiles []model.Profile

	err := r.db.C(r.collection).Find(bson.M{}).All(&profiles)

	if err != nil {
		return nil, err
	}

	return profiles, nil
}
